﻿using System.Linq;
using System.Web.Mvc;
using Citi.Scheduler.Domain;
using Citi.Scheduler.WebUi.Models;

namespace Citi.Scheduler.WebUi.Controllers
{
    public class RoutineRequisiteController : ControllerBase<RoutineRequisiteModel, RoutineRequisite>
    {
        public ActionResult Index(int routineId)
        {
            var configs = new RoutineRequisite().SelectAll<RoutineRequisite>().Where(x => x.RoutineId == routineId).OrderBy(x=> x.Configuration.ConfigurationGroup.Name);

            return PartialView(new RoutineRequisiteModel().CreateModel(configs));
        }

        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public ActionResult Form(int routineId)
        {
            return PartialView(new RoutineRequisiteModel
            {
                RoutineId = routineId
            });
        }

        public ActionResult Delete(int id)
        {
            DeleteBase(id, true);
            return RedirectToAction("Index", new { routineId = id });
        }

        public ActionResult AddConfiguration(RoutineRequisiteModel model, int routineId)
        {
            var routineConfiguration = new RoutineRequisite().SelectAll<RoutineRequisite>()
                                          .FirstOrDefault(x => x.RoutineId == routineId && x.ConfigurationId == model.Id);

            if (routineConfiguration == null)
            {
                routineConfiguration = new RoutineRequisite
                    {
                        ConfigurationId = model.Id,
                        RoutineId = routineId
                    };

                routineConfiguration.Save(routineConfiguration);
            }

            return RedirectToAction("Index", new { routineId });
        }
    }
}
